<?php

namespace app\result\extend;

use app\model\extend\Plugins;
use app\model\extend\UserPlugins;
use app\result\BaseResult;

class PluginsResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Plugins();
    }

    public function list($args = [])
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $where = [];
        if (!empty($args['keyword'])) {
            $where[] = ['name', 'like', '%' . trim($args['keyword']) . '%'];
        }
        $field = 'plugin_id,name,remark,icon,status,path,created_at,updated_at,plugin_tag,min_version,pts';
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, $field, 'plugin_id desc', $page, $pageSize);
        if ($data) {
            foreach ($data as &$item) {
                //状态：1=启用，0=已禁用
                $item['status_text'] = $item['status'] == 1 ? '启用中' : '已禁用';
                $item['pts_text'] = $this->get_pts($item['pts']);
            }
            unset($item);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data
        ]);
    }

    private function get_pts($pts)
    {
        $pts = array_filter(explode(',', $pts));
        $data = [];
        if (!$pts) {
            return ['全部'];
        }
        if (in_array('xcx', $pts)) {
            $data[] = '微信小程序';
        }
        if (in_array('android', $pts)) {
            $data[] = '安卓APP';
        }
        if (in_array('ios', $pts)) {
            $data[] = 'IOS';
        }
        if (in_array('h5', $pts)) {
            $data[] = '移动端H5';
        }
        if (in_array('pc', $pts)) {
            $data[] = 'PC端';
        }
        if (in_array('douyin_xcx', $pts)) {
            $data[] = '抖音小程序';
        }
        if (in_array('qq_xcx', $pts)) {
            $data[] = 'QQ小程序';
        }
        if (in_array('ali_xcx', $pts)) {
            $data[] = '支付宝小程序';
        }
        return $data;
    }

    public function get($args = [])
    {
        $id = intval($args['id'] ?? 0);
        $data = $this->model->data_get(['plugin_id' => $id]);
        $data['pts'] = array_filter(explode(',', $data['pts']));
        $data['content'] = htmlspecialchars_decode($data['content']);
        return $this->success_return('success', $data);
    }

    public function save_data($args): array
    {
        $id = intval($args['plugin_id'] ?? 0);

        $rules = [
            ['name', 'empty|max_length:20|min_length:2', '插件名称不能为空|插件名称长度在2-20位之间|插件名称长度在2-20位之间'],
            ['remark', 'empty|max_length:200|min_length:2', '插件描述不能为空|插件描述长度在4-200位之间|插件描述长度在4-200位之间'],
            ['icon', 'empty', '图标不能为空'],
            ['min_version', 'isset', '最低可用版本未设置'],
            // ['path', 'empty', '插件路径不能为空'],
            ['plugin_tag', 'empty|max_length:20|min_length:2', '插件标识不能为空| 插件标识长度在2-20位之间| 插件标识长度在2-20位之间'],
            ['status', 'isset|in_array:0,1', '请选择状态|状态值不正确'],
            ['content', 'empty', '插件详情不能为空']
        ];
        $check = check_param($args, $rules);
        if ($check['status'] != 0) {
            return self::error_return($check['msg']);
        }
        //标识只能是字母and _
        if (!preg_match('/^[a-zA-Z_]+$/', $args['plugin_tag'])) {
            return self::error_return('标识只能是字母和下划线');
        }
        if ($id) {
            $data = $this->model->data_get(['plugin_id' => $id]);
            if (!$data) {
                return self::error_return('数据不存在');
            }
        }
        if ($this->model->data_get(['plugin_tag' => $args['plugin_tag']])) {
            if (!$id) {
                return self::error_return('标识已存在');
            }
            if ($data['plugin_tag'] != $args['plugin_tag']) {
                return self::error_return('标识已存在');
            }
        }

        //默认全部
        $pts = !empty($args['pts']) ? join(',', $args['pts']) : 'xcx,android,ios,h5,pc,douyin_xcx,qq_xcx,ali_xcx';

        $baseData = [
            'name' => $args['name'] ?? '',
            'remark' => $args['remark'] ?? '',
            'icon' => $args['icon'] ?? '',
            'content' => $args['content'] ?? '',
            'status' => intval($args['status']),
            'path' => $args['path'] ?? '',
            'plugin_tag' => $args['plugin_tag'] ?? '',
            'min_version' => $args['min_version'] ?? '1',
            'pts' => $pts
        ];
        if ($id) {
            $this->model->data_update(['plugin_id' => $id], $baseData);
        } else {
            $this->model->data_add($baseData);
        }
        return $this->success_return('保存成功');
    }

    public function del_data($args): array
    {
        $id = intval($args['id'] ?? 0);
        //判断有没有在使用
        if ((new UserPlugins())->data_get(['plugin_id' => $id])) {
            return $this->error_return('插件有用户正在使用中，无法删除');
        }

        $res = $this->model->data_del(['plugin_id' => $id]);
        return $this->success_return('success');
    }

    public function set_status($args): array
    {
        $id = intval($args['id'] ?? 0);
        $data = $this->model->data_get(['plugin_id' => $id]);
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        $this->model->data_update(['plugin_id' => $id], ['status' => $data['status'] == 0 ? 1 : 0]);
        return $this->success_return('保存成功');
    }
}
